# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
data=pd.read_csv('mnist_train.csv')

#类型装换
def redtype(one):
    one2v=np.zeros(one.shape,dtype='uint8')
    for i in range(one.shape[0]):
        for j in range(one.shape[1]):
            one2v[i][j]=one[i][j]
    return one2v     
#灰度级反转
def resever(image):
    z=np.zeros(image.shape,dtype='uint8')
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            z[i][j]=255-image[i][j]
    return z
#简单二值化
def point(image):
    means=np.mean(image)
    z=np.zeros(image.shape,dtype='uint8')
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            if image[i][j]>means:
                z[i][j]=image[i][j]
            else: 
                z[i][j]=1
    return z       
#裁剪掉空白区域（二值图像的凸包）
def crop(image):
    h=[]
    l=[]
    global a
    global b
    global c
    global d
    for i in range(image.shape[0]):
        avg=np.mean(image[i,:])
        if avg==255:
            h.append(i)
        avg1=np.mean(image[:,i])
        if avg1==255:
            l.append(i)
    for j in range(len(h)-1):
        if h[j+1]-h[j]!=1:
            a=h[j]
            c=h[j+1]
    for k in range(len(l)-1):
        if l[k+1]-l[k]!=1:
            b=l[k]
            d=l[k+1]
    tp=image[a+1:c-1,b+1:d-1]
    return tp
x=np.zeros((len(data),350))
for l in range(len(data)):  
    image=data.iloc[l,1:].values.reshape(28,28)
    image_redtype=redtype(image)
    image_resever=resever(image_redtype)
    image_point=point(image_resever)
    image_crop=crop(image_point)
    tp=image_crop.reshape(1,-1)
    for jj in range(350):
        if jj<tp.size:
            x[l][jj]=tp[0][jj]
        else:
            x[l][jj]=255            
y=data.iloc[:,0] 
data1=pd.read_csv('mnist_test.csv')
x1=np.zeros((len(data1),350))
y1=data1.iloc[:,0]
for m in range(len(data1)):  
    image=data1.iloc[m,1:].values.reshape(28,28)
    image_redtype=redtype(image)
    image_resever=resever(image_redtype)
    image_point=point(image_resever)
    image_crop=crop(image_point)
    tp=image_crop.reshape(1,-1)
    for ii in range(350):
        if ii<tp.size:
            x[m][ii]=tp[0][ii]
        else:
            x[m][ii]=255     
#训练模型和预测数据
from sklearn.neural_network import MLPClassifier  
clf=MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5,2), random_state=1)
clf.fit(x, y);
rv=clf.score(x,y)
R=clf.predict(x1)
Z=R-y1
Rs=len(Z[Z==0])/len(Z)
print('预测结果为：',R)
print('预测准确率为：',Rs)


from sklearn import svm
clf = svm.SVC(kernel='rbf')
clf.fit(x,y)
rv=clf.score(x,y)
R=clf.predict(x1)
Z=R-y1
Rs=len(Z[Z==0])/len(Z)
print('预测结果为：',R)
print('预测准确率为：',Rs)
    
    
    
    
    
    